package com.ptt.sqm.session;

import java.lang.reflect.Type;
import java.util.HashMap;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ptt.sqm.activity.LoginActivity;
import com.ptt.sqm.model.AssessTran;
import com.ptt.sqm.model.Login;
import com.ptt.sqm.util.AppUtil;
import com.ptt.sqmonmobile.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.support.v4.app.ActivityCompat;

public class SessionManager {
	// Shared Preferences
	SharedPreferences pref;

	// Editor for Shared preferences
	Editor editor;

	// Context
	Context _context;

	// Activity
	Activity _activity;

	// Shared pref mode
	int PRIVATE_MODE = 0;

	// Sharedpref file name
	private static final String PREF_NAME = "AndroidSQMPref";

	// All Shared Preferences Keys
	private static final String IS_LOGIN = "IsLoggedIn";

	// (make variable public to access from outside)
	public static final String KEY_NAME = "name";

	public static final String KEY_SETSESSION = "Cookie";
	public static final String KEY_GETSESSION = "Set-Cookie";

	public static final String ERROR_MSG = "ErrorMsg";

	private static final Type MAP_TYPE = new TypeToken<Login>() {
	}.getType();

	private static Login login;

	// Constructor
	public SessionManager(Context context) {
		this._context = context;
		pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
		editor = pref.edit();
	}

	// Constructor
	public SessionManager(Context context, Activity activity) {
		this._context = context;
		this._activity = activity;
		pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
		editor = pref.edit();
	}

	/**
	 * Create login session
	 * */
	public void createLoginSession(Login login) {
		// Storing login value as TRUE
		editor.putBoolean(IS_LOGIN, true);

		// Storing name in pref
		editor.putString(KEY_NAME, new Gson().toJson(login));

		// commit changes
		editor.commit();

		this.login = login;
	}

	public void createCookie(String session) {

		// Storing session in pref
		editor.putString(KEY_SETSESSION, session);

		// commit changes
		editor.commit();
	}

	/**
	 * Check login method wil check user login status If false it will redirect
	 * user to login page Else won't do anything
	 * */
	public void checkLogin() {
		// Check login status
		if (!this.isLoggedIn()) {
			// user is not logged in redirect him to Login Activity
			Intent i = new Intent(_context, LoginActivity.class);
			// Closing all the Activities
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

			// Add new Flag to start new Activity
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

			// Staring Login Activity
			_context.startActivity(i);
		}

	}

	/**
	 * Get stored session data
	 * */
	public Login getUserDetails() {
		login = new Gson().fromJson(pref.getString(KEY_NAME, null), MAP_TYPE);
		return login;
	}

	/**
	 * Get stored session data
	 * */
	public HashMap<String, String> getCookie() {
		HashMap<String, String> user = new HashMap<String, String>();
		// user name
		user.put(KEY_SETSESSION, pref.getString(KEY_SETSESSION, null));

		// return user
		return user;
	}

	/**
	 * Clear session details
	 * */
	public void logoutUser() {
		// Clearing all data from Shared Preferences
		editor.clear();
		editor.commit();

		// After logout redirect user to Loing Activity
		Intent i = new Intent(_context, LoginActivity.class);
		// Closing all the Activities
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

		// Add new Flag to start new Activity
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
			i.addFlags(0x8000);

		// Staring Login Activity
		_context.startActivity(i);
	}

	/**
	 * Clear session details
	 * */
	public void logoutUserWithError() {
		// Clearing all data from Shared Preferences
		_activity.runOnUiThread(new Runnable() {
			public void run() {

				editor.clear();
				editor.commit();

				try {
					new AlertDialog.Builder(_activity).setMessage(_activity.getString(R.string.alert_network_error)).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

							// After logout redirect user to Loing Activity
							Intent i = new Intent(_activity, LoginActivity.class);
							// Closing all the Activities
							i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

							// Add new Flag to start new Activity
							i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

							if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
								i.addFlags(0x8000);

							// Staring Login Activity
							_activity.startActivity(i);
							return;
						}
					}).show();
				} catch (Exception e) {

				}
			}
		});

	}

	/**
	 * Quick check for login
	 * **/
	// Get Login State
	public boolean isLoggedIn() {
		return pref.getBoolean(IS_LOGIN, false);
	}

}
